package com.ibpd.henuocms.tlds;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.*;

import com.ibpd.henuocms.common.IbpdLogger;
/**
 * 循环tag 已废弃
 * @author mg by qq:349070443
 *编辑于 2015-6-20 下午05:44:37
 */
public class WhileHandler extends BodyTagSupport {

	private static final long serialVersionUID = 3553438570162449652L;

	private Object items=null;
	private Iterator itemList=null;
		public int doStartTag () {
			init();
            return BodyTag.EVAL_BODY_BUFFERED;
        }
		private void init(){
            Iterator ite = null;
            
            Object tempItem = items;
            // 如果是集合
            if (tempItem instanceof Collection) {
                ite = ((Collection) tempItem).iterator();
            }
            // 如果是数组
            else if (tempItem instanceof Object[]) {
                ite = Arrays.asList((Object[]) tempItem).iterator();
            }
         // 如果是list
            else if (tempItem instanceof List) {
                ite = ((List)tempItem).iterator();
            }
            itemList=ite;
		}
		private Object getNextObj(){
			if(itemList!=null && itemList.hasNext())
				return itemList.next();
			else
				return null;
		}
        public int doAfterBody () throws JspException {
            Object obj=getNextObj();
            if (obj!=null) {
                this.pageContext.setAttribute("o", obj);
                return IterationTag.EVAL_BODY_AGAIN;
            }else{
            	return  Tag.SKIP_BODY;
            } 
        }

        public int doEndTag () throws JspException {
            try {
               BodyContent bc = getBodyContent ();
               if(!bc.getString().trim().equals("")){
            	   String rtn=bc.getString();
            	   rtn=rtn.replace("\r\n", "");
            	   bc.getEnclosingWriter().write (rtn);
               }
            } catch (IOException ie) {
                throw new JspException (ie.getMessage ());
            }
        return Tag.EVAL_PAGE;
        }

		public void setItems(Object items) {
			IbpdLogger.getLogger(this.getClass()).info(items);
			this.items = items;
		}

		public Object getItems() {
			return items;
		}
}
